package sort.data;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by luoqifei on 2016/11/3.
 */
public class Sort {
    public static class Map extends Mapper<Object,Text,IntWritable,IntWritable> {
        private static IntWritable data = new IntWritable();
        public void map(Object key,Text value, Context context)throws IOException,InterruptedException{
            String line = value.toString();
            data.set(Integer.parseInt(line));
            context.write(data,new IntWritable(1));
        }
    }
    public static class Reduce extends Reducer<IntWritable,IntWritable,IntWritable,IntWritable>{
        private static IntWritable lineNum = new IntWritable(1);
        public void reduce(IntWritable key,Iterable<IntWritable> values,Context context)throws IOException,InterruptedException{

            for(IntWritable value : values){
            context.write(lineNum,key);
                lineNum= new IntWritable(lineNum.get()+1);
            }
        }
    }



    public static void main(String args[]) throws IOException, ClassNotFoundException, InterruptedException {
        String inputPath = "hdfs://localhost:9000/user/sort_input";
        String outputPath="hdfs://localhost:9000/user/sort_output2";
        Configuration conf = new Configuration();
        conf.set("mapred.job.tracker","localhost:9000");
        Job job = new Job(conf,"data sort");
        job.setJarByClass(Sort.class);
        job.setReducerClass(Reduce.class);
        job.setMapperClass(Map.class);
        job.setOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(IntWritable.class);
        FileInputFormat.addInputPath(job,new Path(inputPath));
        FileOutputFormat.setOutputPath(job,new Path(outputPath));
        job.waitForCompletion(true);

    }
}
